// map.js
const app = getApp();
const { locations, pois, routes } = require('../../utils/data.js');
const { getMarkerIconByType, filterPoiByDay, filterPoiByType } = require('../../utils/util.js');

Page({
  data: {
    latitude: 30.53, // 德清中心点
    longitude: 119.95,
    markers: [],
    polylines: [],
    scale: 10,
    showFilter: false,
    filterDay: 0,
    filterType: '',
    allPois: [],
    filteredPois: [],
    currentRoute: null,
    showRouteInfo: false,
    routeDistance: 0,
    routeDuration: 0
  },

  onLoad: function () {
    // 获取用户位置
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        this.setData({
          latitude: res.latitude,
          longitude: res.longitude
        });
      }
    });

    this.setData({
      allPois: pois,
      filteredPois: pois
    });

    this.initMarkers();
  },

  // 初始化地图标记
  initMarkers: function() {
    const markers = this.data.filteredPois.map((poi, index) => {
      return {
        id: index,
        latitude: poi.position[1],
        longitude: poi.position[0],
        iconPath: getMarkerIconByType(poi.type),
        width: 30,
        height: 40,
        callout: {
          content: poi.name,
          color: '#000000',
          fontSize: 12,
          borderRadius: 4,
          padding: 5,
          display: 'BYCLICK',
          textAlign: 'center'
        },
        poiData: poi
      };
    });

    this.setData({
      markers: markers
    });
  },

  // 点击标记
  markerTap: function(e) {
    const markerId = e.detail.markerId;
    const poi = this.data.filteredPois[markerId];
    
    wx.showActionSheet({
      itemList: ['查看详情', '导航到这里'],
      success: (res) => {
        if (res.tapIndex === 0) {
          // 查看详情
          wx.navigateTo({
            url: `/pages/details/poi-detail?id=${poi.id}`
          });
        } else if (res.tapIndex === 1) {
          // 导航
          wx.openLocation({
            latitude: poi.position[1],
            longitude: poi.position[0],
            name: poi.name,
            address: poi.address || '',
            scale: 18
          });
        }
      }
    });
  },

  // 显示/隐藏筛选面板
  toggleFilter: function() {
    this.setData({
      showFilter: !this.data.showFilter
    });
  },

  // 按天数筛选
  filterByDay: function(e) {
    const day = parseInt(e.currentTarget.dataset.day);
    
    this.setData({
      filterDay: day,
      showFilter: false,
      filteredPois: filterPoiByDay(filterPoiByType(this.data.allPois, this.data.filterType), day)
    });
    
    this.initMarkers();
  },

  // 按类型筛选
  filterByType: function(e) {
    const type = e.currentTarget.dataset.type;
    
    this.setData({
      filterType: type,
      showFilter: false,
      filteredPois: filterPoiByType(filterPoiByDay(this.data.allPois, this.data.filterDay), type)
    });
    
    this.initMarkers();
  },

  // 重置筛选
  resetFilter: function() {
    this.setData({
      filterDay: 0,
      filterType: '',
      showFilter: false,
      filteredPois: this.data.allPois
    });
    
    this.initMarkers();
  },

  // 显示路线
  showRoute: function(e) {
    const day = parseInt(e.currentTarget.dataset.day);
    const dayRoutes = routes.filter(r => r.day === day);
    
    if (dayRoutes.length === 0) return;
    
    // 清除当前路线
    this.setData({
      polylines: []
    });
    
    // 获取高德地图API Key
    const key = app.globalData.apiKey;
    
    // 构建路线请求
    dayRoutes.forEach((route, index) => {
      const startPos = locations[route.from];
      const endPos = locations[route.to];
      
      if (!startPos || !endPos) return;
      
      // 使用高德地图驾车路线规划API
      wx.request({
        url: `https://restapi.amap.com/v3/direction/driving?key=${key}&origin=${startPos[0]},${startPos[1]}&destination=${endPos[0]},${endPos[1]}&extensions=all`,
        success: (res) => {
          if (res.data.status === '1' && res.data.route && res.data.route.paths && res.data.route.paths.length > 0) {
            const path = res.data.route.paths[0];
            const distance = path.distance;
            const duration = path.duration;
            
            // 解析路线坐标
            const steps = path.steps;
            let points = [];
            
            steps.forEach(step => {
              const polyline = step.polyline;
              const pointsArr = polyline.split(';');
              
              pointsArr.forEach(point => {
                const [lng, lat] = point.split(',');
                points.push({
                  longitude: parseFloat(lng),
                  latitude: parseFloat(lat)
                });
              });
            });
            
            // 添加路线到地图
            const polylines = this.data.polylines;
            polylines.push({
              points: points,
              color: '#0078FF',
              width: 6,
              arrowLine: true
            });
            
            this.setData({
              polylines: polylines,
              showRouteInfo: true,
              routeDistance: (distance / 1000).toFixed(1),
              routeDuration: (duration / 60).toFixed(0)
            });
            
            // 调整地图视野以包含路线
            this.mapCtx.includePoints({
              points: [
                { latitude: startPos[1], longitude: startPos[0] },
                { latitude: endPos[1], longitude: endPos[0] }
              ],
              padding: [80, 80, 80, 80]
            });
          }
        }
      });
    });
  },

  // 清除路线
  clearRoute: function() {
    this.setData({
      polylines: [],
      showRouteInfo: false
    });
  },

  // 地图加载完成
  mapLoaded: function() {
    this.mapCtx = wx.createMapContext('map');
  }
}) 